"""
小程序登录
"""
import requests
import json
import logging

from .WxConfigParser import ConfigParser


class WeChatLogin:
    def __init__(self):
        con = ConfigParser()
        self.appid = con.get_appid()
        self.secret = con.get_appsecret()
        self.baseUrl = con.get_login_url()

    def get_token(self):
        """
        获取token
        """
        url = self.baseUrl + "cgi-bin/token"
        params = {
            "grant_type": "client_credential",
            "appid": self.appid,
            "secret": self.secret,
            "force_refresh": False
        }
        response = requests.post(url, params=params)
        if response.status_code == 200:
            res_json = response.json()
            if "access_token" in res_json.keys():
                return res_json["access_token"]
            else:
                raise ValueError(json.dumps(res_json))

    def get_user_phone_number(self, code):
        """
        获取用户手机信息
        @code 小程序发来的code a1f420c6e4757a9dfe70eb3c0ddada957932426f4f2155870e9ed3a54b5136ed
        """
        url = self.baseUrl + "wxa/business/getuserphonenumber"
        access_token = self.get_token()
        querystring = {"access_token": access_token}
        payload = {
            "code": code
        }
        payload = json.dumps(payload)
        headers = {'Content-Type': 'application/json'}
        response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
        return eval(response.text)
